from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse
# Create your views here.
from .models import *
from django.conf import settings
from datetime import datetime
from random import randint
import json
import base64
from django.db.models import Q, F
import xlwt
import io
from urllib.parse import quote
from django.core.paginator import Paginator, EmptyPage

def 获取所有用户(request):
    if request.method == 'GET':
        return JsonResponse({
            'code': 200,
            'messages': '获取用户列表成功！',
            'userlist': list(User.objects.values('id', 'username', 'mobile', 'isDelete'))
        })

def 更改用户状态(request):
    if request.method == 'GET':
        data = request.GET
        id = data.get('id')
        isDelete = data.get('isDelete')
        user = User.objects.get(id=id)
        user.isDelete = isDelete
        user.save()
        return JsonResponse({
            'code': 200,
            'messages': '操作成功！',
            'userlist': list(User.objects.values('id', 'username', 'mobile', 'isDelete'))
        })

def 获取所有分类(request):
    if request.method == 'GET':
        return JsonResponse({
            'code': 200,
            'messages': '获取分类列表成功！',
            'categorylist': list(Category.objects.values('id', 'categoryName'))
        })

def 添加分类(request):
    if request.method == 'POST':
        categoryName = request.POST.get('categoryName')
        Category.objects.create(categoryName=categoryName)
        return JsonResponse({
            'code': 200,
            'messages': '操作成功！',
            'categorylist': list(Category.objects.values('id', 'categoryName'))
        })

def 添加二级分类(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        imgData = data.get('imgData')
        imgName = data.get('imgName')
        categoryId = data.get('categoryId')
        brandName = data.get('brandName')
        if imgData:
            with open(fr"{settings.UPLOAD_ROOT}/{imgName}", 'wb') as f:
                f.write(base64.b64decode(imgData))
                f.close()
            try:
                Brand.objects.create(superior_id=categoryId, brandName=brandName, imgName=f'upload/{imgName}')
            except:
                return JsonResponse({'code': 400, 'message': '操作失败!'})
            else:
                return JsonResponse({'code': 200, 'message': '添加分类成功!'})
        else:
            return JsonResponse({'code': 401, 'message': '获取图片数据失败!'})

def 获取所有品牌(request):
    if request.method == 'GET':
        return JsonResponse({
            'code': 200,
            'messages': '获取品牌列表成功！',
            'brandlist': list(Brand.objects.annotate(categoryName=F('superior__categoryName'))\
                              .values('id', 'categoryName', 'brandName', 'imgName'))
        })

def 添加商品(request):
    if request.method == 'POST':
        proName = request.POST.get('proName')
        brandId = request.POST.get('brandId')
        proDesc = request.POST.get('proDesc')
        num = request.POST.get('num')
        size = request.POST.get('size')
        price = request.POST.get('price')
        oldPrice = request.POST.get('oldPrice')
        try:
            Product.objects.create(proName=proName, proBrand_id=brandId, proDesc=proDesc, num=num, price=price, oldPrice=oldPrice, size=size)
            return JsonResponse({'code': 200, 'messages': '操作成功！'})
        except:
            return JsonResponse({'code': 400, 'messages': '操作失败！'})

def 获取所有商品(request):
    if request.method == 'GET':
        data = request.GET
        if not data:
            return JsonResponse({
                'code': 200,
                'messages': '获取品牌列表成功！',
                'productlist': list(Product.objects.annotate(proBrandName=F('proBrand__brandName'))\
                                  .values('id', 'proName', 'proBrandName', 'proDesc', 'num', 'size', 'price', 'oldPrice', 'statu'))
            })
        else:
            pagesize = int(data.get('pagesize'))
            pageno = int(data.get('pageno'))
            keywords = data.get('keywords')
            # 分页过滤部分
            try:
                # values()获取到全部字段，只需要填写需要的字段即可
                QuerySet对象 = Product.objects.annotate(proBrandName=F('proBrand__brandName'))\
                    .values('id', 'proName', 'proBrandName', 'proDesc', 'num', 'size', 'price', 'oldPrice', 'statu')\
                    .order_by('-id')
                if keywords:
                    # 指定在商品名中查找
                    conditions = [Q(proName__contains=one) for one in keywords.split(' ') if one]
                    query = Q()
                    for condition in conditions:
                        query |= condition
                    QuerySet对象 = QuerySet对象.filter(query)
                # 使用分页对象，设定每页多少条记录
                page_all = Paginator(QuerySet对象, pagesize)
                # 从数据库中读取数据，指定读取其中第几页
                page_no = page_all.page(pageno)
                # 将 QuerySet 对象 转换成list类型
                商品列表 = list(page_no)
                # total 返回总共有多少个符合条件的商品
                return JsonResponse({'code': 200, 'productlist': 商品列表, 'total': page_all.count, 'message': '获取商品列表成功！'})
            except EmptyPage:
                return JsonResponse({'code': 401, 'productlist': [], 'total': 0, 'message': '没有这一页！'})
            except:
                return JsonResponse({'code': 400, 'message': '获取商品信息失败！'})

def 更改商品状态(request):
    if request.method == 'POST':
        data = request.POST
        id = data.get('id')
        print(id)
        statu = data.get('statu')
        print(statu)
        product = Product.objects.get(id=id)
        product.statu = statu
        product.save()
        return JsonResponse({'code': 200, 'messages': '操作成功！'})

def 生成Excel报表(request):
    if request.method == 'GET':
        queryset = Product.objects.all()
        wb = xlwt.Workbook()
        sheet = wb.add_sheet('商品表')
        titles = ('编号', '商品名称', '品牌', '商品描述', '库存', '价格', '原价', '尺寸', '状态')
        for col_index, title in enumerate(titles):
            sheet.write(0, col_index, title)
        for row_index, product in enumerate(queryset):
            sheet.write(row_index + 1, 0, product.id)
            sheet.write(row_index + 1, 1, product.proName)
            sheet.write(row_index + 1, 2, product.proBrand.brandName)
            sheet.write(row_index + 1, 3, product.proDesc)
            sheet.write(row_index + 1, 4, product.num)
            sheet.write(row_index + 1, 5, product.price)
            sheet.write(row_index + 1, 6, product.oldPrice)
            sheet.write(row_index + 1, 7, product.size)
            sheet.write(row_index + 1, 8, '已上架' if product.statu else '已下架')
        buffer = io.BytesIO()
        wb.save(buffer)
        resp = HttpResponse(buffer.getvalue(), content_type='application/vnd.ms-excel')
        filename = quote('商品汇总统计.xls')
        # attachment表示以附件的形式进行下载
        # 由于不能直接用单引号 ’ 所以需要做转义处理:\'
        resp['content-disposition'] = f'attachment; filename*=utf-8\'\'{filename}'
        return resp